import { ref, computed, reactive } from 'vue';
import { trading } from '@/server/trading';
import { assetService, holding_list } from '@/service/asset';
import { toast } from '@/service/status';
import { userInfo, userService } from '@/service/user';
import { stock_detail_data, market_status, stock_list } from '@/service/market';
import { user } from '@/server/user';

export const show_trading_selector = ref(false);
export const show_stock_close_selector = ref(false);

export const order_type = [
    {
        id: 0,
        name: "Market"
    },
    {
        id: 1,
        name: "Limit"
    }
];

export const trade_type = [
    {
        id: 1,
        name: 'Buy'
    },
    {
        id: 2,
        name: 'Sell'
    }
];

export const order_type_selected = ref(order_type[0].id);

export const trade_type_selected = ref(trade_type[0]);

export const quantity = ref(1);

export const input_price = ref(0);

// 总价格
export const total_price = computed(() => {
    if (!active_stock.value) return '0.00';
    let price = active_stock.value?.price?.slice(1);
    return `$${ (price * quantity.value).toFixed(2) }`;
});

export function subQuantity() {
    let num = parseInt(quantity.value);
    if (num > 1) {
        quantity.value = num - 1;
    }
}

export function addQuantity() {
    let num = parseInt(quantity.value);
    quantity.value = num + 1;
}

export function openTradingSelector(type) {
    trade_type_selected.value = type;
    show_trading_selector.value = true;
}

export function openStockCloseSelector(type) {
    trade_type_selected.value = type;
    show_stock_close_selector.value = true;
}

export function closeTradingSelector() {
    show_trading_selector.value = false;
}

export function closeStockCloseSelector() {
    show_stock_close_selector.value = false;
}

// 取消限价订单窗口
export const cancelLimitPage = reactive({
    show: false,
    id: '',
    open(id) {
        cancelLimitPage.id = id;
        cancelLimitPage.show = true;
    },
    close() {
        cancelLimitPage.id = '';
        cancelLimitPage.show = false;
    },
});

export const active_stock = ref({
    id: '',
    symbol: '',
    name: '',
    shortName: '',
    country: '',
    exchange: '',
    minTrade: '',
    type: '',
    tradeStatus: '',
    price: '$0.00',
    change: '+0.00%',
    volume: 0,
    market_cap: '0.00B',
    more: [
        {
            id: 1,
            k: 'Previous Close',
            v: '$0.00',
        },
        {
            id: 2,
            k: 'Open',
            v: '$0.00',
        },
        {
            id: 3,
            k: 'Day Range',
            v: '0.00 - 0.00',
        },
        {
            id: 4,
            k: 'Volume',
            v: '0.00'
        }
    ]
});

export const active_stock_close_item = ref({
    id: '',
    symbol: '',
    name: '',
    shares: '',
    price: '',
    limitQuantity: '',
    marketSymbol: '',
    avgPrice: '',
    marketCap: '',
    orderSide: '',
    status: '',
    openTime: '',
});

export const tradingService = {
    async stockOpen(shortName) {
        let marketId = stock_detail_data.value.id;
        let count = quantity.value;
        let openType = order_type_selected.value;
        let price = input_price.value.toFixed(2);
        let res = await trading.stockOpen(marketId, count, openType, openType == 1 ? price : null);
        if (res.success) {
            if (res.data.code == 200) {
                toast.success(`Succee to buy ${ count } shares of ${ shortName }`, 2000);
                assetService.getStockOrderList();
                userService.getUserInfo();
            } else if (res.data.code == 401) {
                toast.warning('Trading Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Trading failed!');
            }
        } else {
            if (res.err.message == 'token is null') {
                toast.warning('Trading Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Trading failed!');
            }
        }
    },
    async stockClose(symbolId, shortName) {
        let marketId = symbolId;
        let count = quantity.value;
        let openType = order_type_selected.value;
        let price = input_price.value;
        let res = await trading.stockClose(marketId, count, openType, openType == 1 ? price : null);
        if (res.success) {
            if (res.data.code == 200) {
                toast.success(`Succee to sell ${ count } shares of ${ shortName }`, 2000);
                assetService.getStockOrderList();
                userService.getUserInfo();
            } else if (res.data.code == 401) {
                toast.warning('Trading Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Trading failed!');
            }
        } else {
            if (res.err.message == 'token is null') {
                toast.warning('Trading Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Trading failed!');
            }
        }
    },
    // 用于区别普通的开仓接口 所以采用传递参数的方式来实现
    async quickBuy(symbolId, count) {
        // 获取更多信息 - 未来应该优化到 O(1)
        let minTrade = 1;      // 最小交易股数
        let shortName = '';    // 股票简称
        for (let i = 0; i < stock_list.value.length; i++) {
            let item = stock_list.value[i];
            if (item.id == symbolId) {
                minTrade = item.minTrade;      // 最小交易股数
                shortName = item.shortName;    // 股票简称
                break;
            }
        }
        // 校验市场关闭
        if (!market_status.close) {
            toast.warning('Stocks cannot be sold during market closures.', 1500);
            return ;
        }
        // 校验参数
        if (!symbolId) {
            toast.warning('Please input Symbol', 1500);
            return ;
        }
        count = parseInt(count);
        if (!count) {
            toast.warning('Please input quantity', 1500);
            return ;
        }
        // 校验最低交易股数
        if (count < minTrade) {
            toast.warning(`The minimum trading shares is ${ minTrade }`, 1500);
            return ;
        }
        // 校验账户余额
        let price = parseFloat(stock_detail_data.value.price.slice(1));
        if (parseFloat(userInfo.balance) < price * count) {
            toast.warning('Your balance is insufficient', 1500);
            return ;
        }
        // 快速交易仅限市价交易
        let res = await trading.stockOpen(symbolId, count, 0, null);
        if (res.success) {
            if (res.data.code == 200) {
                toast.success(`Succee to buy ${ count } shares of ${ shortName }`, 2000);
                assetService.getStockOrderList();
                userService.getUserInfo();
            } else if (res.data.code == 401) {
                toast.warning('Trading Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Trading failed!');
            }
        } else {
            if (res.err.message == 'token is null') {
                toast.warning('Trading Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Trading failed!');
            }
        }
    },
    // 用于区别普通的平仓接口 所以采用传递参数的方式来实现
    async quickSell(symbolId, count) {
        // 获取更多信息 - 未来应该优化到 O(1)
        let marketId = 0;
        let shortName = '';          // 股票简称
        let self_stock_count = 0;    // 持有股数
        for (let i = 0; i < stock_list.value.length; i++) {
            let item = stock_list.value[i];
            if (item.id == symbolId) {
                shortName = item.shortName;       // 股票简称
                break;
            }
        }
        for (let i = 0; i < holding_list.value.length; i++) {
            let item = holding_list.value[i];
            if (item.symbol == shortName) {
                marketId = item.id;
                self_stock_count = item.shares;   // 持有股数
                break;
            }
        }
        // 校验市场关闭
        if (!market_status.close) {
            toast.warning('Stocks cannot be sold during market closures.', 1500);
            return ;
        }
        // 校验参数
        if (!symbolId) {
            toast.warning('Please input Symbol', 1500);
            return ;
        }
        count = parseInt(count);
        if (!count) {
            toast.warning('Please input quantity', 1500);
            return ;
        }
        // 校验持仓记录
        if (self_stock_count < count) {
            toast.warning(`The quantity of ${ shortName } is insufficient.`, 2000);
            return ;
        }
        // 快速交易仅限市价交易
        let res = await trading.stockClose(marketId, count, 0, null);
        if (res.success) {
            if (res.data.code == 200) {
                toast.success(`Succee to sell ${ count } shares of ${ shortName }`, 2000);
                assetService.getStockOrderList();
                userService.getUserInfo();
            } else if (res.data.code == 401) {
                toast.warning('Trading Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Trading failed!');
            }
        } else {
            if (res.err.message == 'token is null') {
                toast.warning('Trading Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Trading failed!');
            }
        }
    },
    async cancelOpenOrder(id) {
        let res = await trading.cancelOpenOrder(id);
        if (res.success) {
            if (res.data.code == 200) {
                toast.success(`Succee to cancel`, 2000);
                // 取消成功后重新获取数据
                assetService.getStockOrderList();
                assetService.getStockOpenList();
                userService.getUserInfo();
            } else if (res.data.code == 401) {
                toast.warning('Cancel Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Cancel failed!');
            }
        } else {
            if (res.err.message == 'token is null') {
                toast.warning('Cancel Failed! Please try again after login!', 2000);
            } else {
                toast.warning('Cancel failed!');
            }
        }
    }
};